<?php

require_once 'classes/LightPressPlugin.php';

class PostAdRecursion extends LightPressPlugin {
    
    var $constructor_args = array(
        'templates'=>'a list of post numbers and templates using the following format 1:ad_template,2:ad_template,3:ad_template',
        'templates_folder'=>'folder where the templates are, levae empty to use the plugins/ folder and prepend post_ad_recursion_ to the template names');
    var $default_context = 7; // LP_CONTEXT_INDEX | LP_CONTEXT_ARCHIVES | LP_CONTEXT_CATEGORY;
    var $description = 'Display a template between posts in the index. The template is called post_ad_recursion_n.xml, where n is the index of the post preceding the template, eg post_ad_recursion_3.xml post_ad_recursion_6.xml etc.';
    

    var $active = true;
    var $hooks = array('parse_post');

    var $templates = '';
    var $templates_folder = '';
    
    var $_templates;
    
    var $_loop_cycle = 0;

    function PostAdRecursion(&$frontend, $args, $dummy_run=false) {
        $this->LightPressPlugin($frontend, $args, $dummy_run);

        if (!$dummy_run) {
            
            $templates_folder = $this->templates_folder;
            $s = substr($templates_folder, -1);
            
            if (!empty($s) && $s != DIRECTORY_SEPARATOR && $s != '/')
                $templates_folder .= DIRECTORY_SEPARATOR;
            
            foreach (preg_split('/\s*,\s*/', $this->templates) as $k) {
                $tokens = explode(':', $k);
                if (count($tokens) != 2)
                    continue;
                if (empty($templates_folder))
                    $template = "plugins/post_ad_recursion_{$tokens[1]}.xml";
                else
                    $template = "$templates_folder{$tokens[1]}.xml";
                $this->_templates[(int)$tokens[0]] = $template;
            }
            
            if (count($this->_templates) == 0)
                $active = false;

        }
    }

    function hide() {
        return;
    }
    
    function run($hook, &$post) {
        $this->_loop_cycle++;
        if (!isset($this->_templates[$this->_loop_cycle]))
            return;
        $tpl =& $this->_frontend->tpl;
        $template = $this->_templates[$this->_loop_cycle];

        $tpl->setFile("plugin_postadrecursion_{$this->_loop_cycle}", $template);
        $tpl->parse('BLOCK_POST', "plugin_postadrecursion_{$this->_loop_cycle}", true, false);
    }

}

?>